//
//  DeviceFullChartController.m
//  RuiHeApp
//
//  Created by Jun on 2022/11/13.
//

#import "DeviceFullChartController.h"
#import "DevParamsAlertController.h"
#import "DeviceChartFieldModel.h"
#import "RHWindowTipManage.h"
#import "DeviceChartView.h"
#import "DevChartModel.h"
#import "RHDeviceModel.h"
#import "AppDelegate.h"
#import "WSDatePickerView.h"
#import "RHEndPointModel.h"


@interface DeviceFullChartController ()

@property (nonatomic ,strong) DeviceChartView *chartView;

@property (nonatomic ,strong) DevChartModel *chartModel;

@property (nonatomic ,assign) DevChartType chartType;

@property (nonatomic ,assign) NSInteger toolType;

@property (nonatomic ,strong) RHDeviceModel *devModel;

@property (nonatomic ,strong)RHEndPointModel *endPointModel;
@end

@implementation DeviceFullChartController

- (instancetype)initWithModel:(DevChartModel *)chartModel devModel:(RHDeviceModel *)devModel chartType:(DevChartType)type  toolType:(NSInteger)toolType endPointModel:(RHEndPointModel*)endPointModel{
    self = [super init];
    if (self) {
        self.chartModel = chartModel;
        self.chartType = type;
        self.devModel = devModel;
        self.toolType = toolType;
        self.endPointModel = endPointModel;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
//    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//       delegate.allowRotate = 0;
//    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
//    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
//    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
//         SEL selector = NSSelectorFromString(@"setOrientation:");
//         NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
//         [invocation setSelector:selector];
//         [invocation setTarget:[UIDevice currentDevice]];
//         int val = UIInterfaceOrientationPortrait;
//         [invocation setArgument:&val atIndex:2];
//         [invocation invoke];
//     }
    //[self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.allowRotate = 1;
    //NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    //[[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    
    if(@available(iOS 16.0, *)) {
        [self.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *ws = (UIWindowScene *)array[0];
        UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
        geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskLandscapeRight;
        [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
             //业务代码
        }];
    }else{
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:UIColor.whiteColor];
    [self.navigationController.view setBackgroundColor:UIColor.whiteColor];
    self.navigationItem.title = @"Full Chart";
    self.isUnPopGes = YES;
    [self setupUI];
    [_chartView setHidden:YES];
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleDeviceOrientationDidChange:)
                                                     name:UIDeviceOrientationDidChangeNotification
                                                   object:nil];
}

- (void)dealloc{
    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                        name:UIDeviceOrientationDidChangeNotification
                                                      object:nil];
}

- (void)setupUI{
    _chartView = [[DeviceChartView alloc] initWithFrame:CGRectMake(kStatusBarSafeMargin, 0,kUI_WINDOW_H - kStatusBarSafeMargin,kUI_WINDOW_W - kTabbarSafeBottomMargin) type:self.toolType withIsLandscape:YES];
    _chartView.isLandscape = YES;
    [self.view addSubview:_chartView];
    kWeakSelf;
    _chartView.fullChartBlock = ^{
        AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
           delegate.allowRotate = 0;
        if(@available(iOS 16.0, *)) {
            [weakSelf.navigationController setNeedsUpdateOfSupportedInterfaceOrientations];
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *ws = (UIWindowScene *)array[0];
            UIWindowSceneGeometryPreferencesIOS *geometryPreferences = [[UIWindowSceneGeometryPreferencesIOS alloc] init];
            geometryPreferences.interfaceOrientations = UIInterfaceOrientationMaskPortrait;
            [ws requestGeometryUpdateWithPreferences:geometryPreferences errorHandler:^(NSError * _Nonnull error) {
                 //业务代码
            }];
        }else{
            NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
        weakSelf.chartModel.isAllowScale = NO;
        
    };
    
    _chartView.selectTopToolBlock = ^(NSInteger index) {
        [weakSelf selectTopTool:index];
    };
    
    _chartView.subTimeBlock = ^{
        [weakSelf subTimeAction];
    };
    
    _chartView.addTimeBlock = ^{
        [weakSelf addTimeAction];
    };

    _chartView.changeTimeBlock = ^{
        [weakSelf changeDate];
    };
    
    [_chartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(5);
        make.right.mas_offset(-5);
        make.top.mas_offset(5);
        make.bottom.mas_offset(0);
    }];

   
    [self.chartView setChartModel:self.chartModel];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (weakSelf.chartModel.timeType == TimeType_Day) {
            [weakSelf getDataFromNetwork:weakSelf.chartModel];
        }
        if (weakSelf.chartModel.timeType == TimeType_Month) {
//            [weakSelf getYearOrMonth:YES model:weakSelf.chartModel];
        }
        if (weakSelf.chartModel.timeType == TimeType_Year) {
//            [weakSelf getYearOrMonth:NO model:weakSelf.chartModel];
        }
        
    });
}

#pragma mark Action - Method
- (void)addTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    if (self.chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:self.chartModel];
    }else if (self.chartModel.timeType == TimeType_Month){
//        [self getYearOrMonth:YES model:self.chartModel];
    }else if (self.chartModel.timeType == TimeType_Year){
//        [self getYearOrMonth:NO model:self.chartModel];
    }
}

- (void)subTimeAction{
    if (self.chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (self.chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (self.chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (self.chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    if (self.chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:self.chartModel];
    }else{
        [_chartView setChartModel:_chartModel];
    }

}

- (void)selectTopTool:(NSInteger)index {
    if (index == -1) {//Params
        DevParamsAlertController *vc = [[DevParamsAlertController alloc] initWithModel:self.chartModel isFull:YES];
        if(@available(iOS 16.0, *)) {
            [self presentViewController:vc animated:NO completion:nil];
        }else{
            [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
        }
        kWeakSelf;
        vc.resultBlock = ^{
            [weakSelf updateParams:weakSelf.chartModel];
        };
        return;
        
    }

    if (index == 0) {//Day
        self.chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.params = self.chartModel.dayParams;
        [self getDataFromNetwork:self.chartModel];
        return;

    }
    
    if (index == 1) {//Month
        self.chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.allDataArray = @[];
        self.chartModel.params = self.chartModel.monthParams;
        [self.chartView setChartModel:self.chartModel];
//        [self getYearOrMonth:YES model:self.chartModel];
        return;
    }
    
    if (index == 2) {//Year
        self.chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        self.chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        self.chartModel.allDataArray = @[];
        self.chartModel.params = self.chartModel.yearParams;
        [self.chartView setChartModel:self.chartModel];
//        [self getYearOrMonth:NO model:self.chartModel];
        return;
    }
    
    if (index == 4) {//Total
        //self.chartModel.timeType = TimeType_Total;
        return;
    }
}
 
//变更日期
- (void)changeDate{
    DevChartModel *chartModel = self.chartModel;
    //NSString *dateFormatStr = @"yyyy-MM-dd HH:mm";
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYearMonthDay;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        if (chartModel.timeType == TimeType_Day) {
            [self getDataFromNetwork:chartModel];
        }else if (chartModel.timeType == TimeType_Month){
            [self.chartView setChartModel:chartModel];
//            [self getYearOrMonth:YES model:self.chartModel];
        }else if (chartModel.timeType == TimeType_Year){
            [self.chartView setChartModel:chartModel];
//            [self getYearOrMonth:NO model:self.chartModel];
        }
    }];
    datePickerV.dateLabelColor = UIColor.blueColor;//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
 
- (void)updateParams:(DevChartModel *)chartModel{
    
    if (chartModel.timeType == TimeType_Day) {
        [self getDataFromNetwork:chartModel];
    }else if (chartModel.timeType == TimeType_Month){
        [self getYearOrMonth:YES model:chartModel];
    }else if (chartModel.timeType == TimeType_Year){
        [self getYearOrMonth:NO model:chartModel];
    }
}


#pragma mark - Network
- (void)getDataFromNetwork:(DevChartModel *)chartModel{
    
    if (!self.devModel) {
        return;
    }
    
    if(!self.endPointModel){
        NSLog(@"------->请选择子端点");
        return;
    }
   
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    
    NSMutableArray *keys = [NSMutableArray array];
    for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
        [keys addObject:fileld.keyCode];
    }

    NSMutableDictionary *para = @{@"deviceId":self.devModel.deviceId,
                           @"endpointTypeCode":self.endPointModel.endpointCode,
                           @"keyCodes":keys,
                           @"endpointSn":self.endPointModel.sn,
                           @"startTimestamp":begin_time,
                           @"endTimestamp":end_time
    }.mutableCopy;
    
    //逆变器带EMU类型的参数特殊处理
    NSString *url = D_getEndpointDataByTime;
    
    if ([self.endpointType containsString:@"InvVoltronicLv"]||
        [self.endpointType containsString:@"InvMegarevoLv"]) {
        url = D_getInvEndpointDataByTime;
        
        NSMutableArray *emuKeys = [NSMutableArray array];
        NSMutableArray *invKeys = [NSMutableArray array];
        [keys enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj containsString:@"InvVoltronicLv"]) {
                [invKeys addObject:obj];
            }
            if ([obj containsString:@"Emu"]) {
                [emuKeys addObject:obj];
            }
        }];
        para = @{@"deviceId":self.devModel.deviceId,
                 @"startTimestamp":begin_time,
                 @"endTimestamp":end_time,
                 @"dateRange":@"day"
        }.mutableCopy;
        if (emuKeys.count>0) {
            [para setObject:ValidNullData(self.emuSN) forKey:@"emuSn"];
            [para setObject:emuKeys forKey:@"emuKeyCode"];
        }
        if (invKeys.count>0) {
            [para setObject:self.endPointModel.sn forKey:@"invSn"];
            [para setObject:invKeys forKey:@"invKeyCode"];
        }
    }
    
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:url argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            if([request.responseObject[@"data"] isKindOfClass:[NSArray class]]){
            
                NSArray *dataArr = request.responseObject[@"data"];
                
                //为了让图表显示,造点假数据
                if(dataArr.count == 0){
                    NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
                    [keys enumerateObjectsUsingBlock:^(NSString  *_Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
                        [mtbDic setObject:@"" forKey:key];
                    }];
                    [mtbDic setObject:@"" forKey:@"time"];
                   
                    chartModel.allDataArray = @[mtbDic];
                }else{
                    chartModel.allDataArray = dataArr;
                }
                
                [self.chartView setChartModel:chartModel];
            }
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
         
        
    }];
}

//获取年月数据
/*- (void)getYearOrMonth:(BOOL)isMonth model:(DevChartModel *)chartModel{
    
    if (!self.devModel) {
        return;
    }
    NSString *url = [NSString stringWithFormat:@"%@/%@/data",H_getDevData,self.devModel.devid];
    //NSDictionary *dic = @{@"E_cumchgcap":@{@"$exists": @(1)}};
    NSMutableDictionary *fields_dic = [NSMutableDictionary dictionary];
    NSMutableDictionary *filter_dic = [NSMutableDictionary dictionary];
    for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
        [fields_dic setObject:@(1) forKey:fileld.nickname];
        [filter_dic setObject:@{@"$exists": @(1)} forKey:fileld.nickname];
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    
    [fields_dic setObject:@(1) forKey:@"time"];
    [fields_dic setObject:@(1) forKey:@"E_year"];
    [fields_dic setObject:@(1) forKey:@"E_mon"];
    [fields_dic setObject:@(1) forKey:@"E_day"];
    
    [filter_dic setObject:isMonth?@(date.month):@(date.year-2000) forKey:isMonth?@"E_mon":@"E_year"];
    
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:1 hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:[date daysInMonth] hour:23 minute:59 second:59];
    if (!isMonth) {
        begin_date = [NSDate dateWithYear:date.year month:1 day:1 hour:0 minute:0 second:0];
        end_date = [NSDate dateWithYear:date.year month:date.month day:[date daysInMonth] hour:23 minute:59 second:59];
    }
    NSString *begin_time = [NSString stringWithFormat:@"%d",(int)[begin_date timeIntervalSince1970]];
    NSString *end_time = [NSString stringWithFormat:@"%d",(int)[end_date timeIntervalSince1970]];
    
    NSDictionary *params = @{@"devtype":self.devModel.devtype,
                             @"devid":self.devModel.devid,
                             @"datatype": @"data",
                             @"starttime":begin_time,
                             @"endtime": end_time,
                             @"fields": [fields_dic yy_modelToJSONString],
                             @"filter": [filter_dic yy_modelToJSONString],
                             @"descend":@(0),
                             @"skip":@(0),
                             @"limit":@(20000),
                             @"isReturn":@(1)};
    [SVProgressHUD show];
    [BaseModel startGetWithCompletionAPIKey:url argument:params requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [SVProgressHUD dismiss];
        if (resultModel.success) {
            NSLog(@"----%@",resultModel.data);
            chartModel.allDataArray = resultModel.data;
            [self.chartView setChartModel:chartModel];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [[ProgressHUDManage shareObject] showAlert:ValidStr(resultModel.message)?resultModel.message:@"request error"];
            [SVProgressHUD dismiss];
    }];
}*/

//获取年月数据
- (void)getYearOrMonth:(BOOL)isMonth model:(DevChartModel *)chartModel{
    
    if (!_devModel) {
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@/data",@"H_getDevData",self.devModel.deviceId];
    //NSDictionary *dic = @{@"E_cumchgcap":@{@"$exists": @(1)}};
    NSMutableDictionary *fields_dic = [NSMutableDictionary dictionary];
    NSMutableDictionary *filter_dic = [NSMutableDictionary dictionary];
    NSDictionary *dayDic = @{@"$dateToString":@{@"format":isMonth?@"%Y-%m-%d":@"%Y-%m",
                                                @"date":@{@"$toDate":@"$time"},
                                                @"timezone":@"Asia/Shanghai"}};
    NSMutableDictionary *projectDic = [NSMutableDictionary dictionary];
    [projectDic setObject:@(0) forKey:@"_id"];
    [projectDic setObject:dayDic forKey:@"day"];
    
    for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
        [fields_dic setObject:@(1) forKey:fileld.keyName];
        [filter_dic setObject:@{@"$exists": @(1)} forKey:fileld.keyName];
        [projectDic setObject:[NSString stringWithFormat:@"$%@",fileld.keyName] forKey:fileld.keyName];
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    
    [fields_dic setObject:@(1) forKey:@"time"];
    [projectDic setObject:@"$time" forKey:@"time"];
//    [fields_dic setObject:@(1) forKey:@"E_year"];
//    [fields_dic setObject:@(1) forKey:@"E_mon"];
//    [fields_dic setObject:@(1) forKey:@"E_day"];
    
//   [filter_dic setObject:isMonth?@(date.month):@(date.year-2000) forKey:isMonth?@"E_mon":@"E_year"];

    NSDictionary *sort1Dic = @{@"$sort":@{@"time":@(1)}};
    NSDictionary *groupDic =  @{@"$group":@{@"_id":@"$day",@"first":@{@"$first":@"$$ROOT"},@"last":@{@"$last":@"$$ROOT"}}};
    NSDictionary *sort2Dic = @{@"$sort":@{@"_id":@(1)}};
    NSArray *aggregation = @[@{@"$project":projectDic},
                             sort1Dic,
                             groupDic,
                             sort2Dic];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:1 hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:[date daysInMonth] hour:23 minute:59 second:59];
    
    if (!isMonth) {
        begin_date = [NSDate dateWithYear:date.year month:1 day:1 hour:0 minute:0 second:0];
        end_date = [NSDate dateWithYear:date.year month:date.month day:[date daysInMonth] hour:23 minute:59 second:59];
    }
    NSString *begin_time = [NSString stringWithFormat:@"%d",(int)[begin_date timeIntervalSince1970]];
    NSString *end_time = [NSString stringWithFormat:@"%d",(int)[end_date timeIntervalSince1970]];
    
    NSDictionary *params = @{@"devtype":self.devModel.deviceTypeCode,
                             @"devid":self.devModel.deviceId,
                             @"datatype": @"data",
                             @"starttime":begin_time,
                             @"endtime": end_time,
                             @"fields": [fields_dic yy_modelToJSONString],
                             @"filter": [filter_dic yy_modelToJSONString],
                             @"aggregation":[aggregation yy_modelToJSONString],
                             @"descend":@(0),
                             @"skip":@(0),
                             @"limit":@(20000),
                             @"isReturn":@(1)};
    [SVProgressHUD show];
    [BaseModel startGetWithCompletionAPIKey:url argument:params requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [SVProgressHUD dismiss];
        if (resultModel.success) {
            
            //chartModel.allDataArray = resultModel.data;
            chartModel.mYDataArray = resultModel.data;
            [self.chartView setChartModel:chartModel];
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [ProgressHUDManage showError:ValidStr(resultModel.message)?resultModel.message:@"request error"];
            [SVProgressHUD dismiss];
    }];
}


- (void)handleDeviceOrientationDidChange:(UIInterfaceOrientation)interfaceOrientation
{
    UIDevice *device = [UIDevice currentDevice] ;
    
    switch (device.orientation) {
        case UIDeviceOrientationFaceUp:
            NSLog(@"屏幕朝上平躺");
            break;
            
        case UIDeviceOrientationFaceDown:
            NSLog(@"屏幕朝下平躺");
            break;
            
        case UIDeviceOrientationUnknown:
            NSLog(@"未知方向");
            break;
            
        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"屏幕向左横置");
            break;
            
        case UIDeviceOrientationLandscapeRight:
            NSLog(@"屏幕向右橫置");
            break;
            
        case UIDeviceOrientationPortrait:
            NSLog(@"屏幕直立");
            break;
            
        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"屏幕直立，上下顛倒");
            break;
            
        default:
            NSLog(@"无法辨识");
            break;
    }
}




#pragma mark -  Autorotate 横竖屏控制
//是否可以旋转
- (BOOL)shouldAutorotate{
    return NO;
}

//支持的方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;//上左右
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;//上左右
}


#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                duration:(NSTimeInterval)duration {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
       toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        [_chartView mas_updateConstraints:^(MASConstraintMaker *make) {
           
            make.left.mas_offset(toInterfaceOrientation == UIInterfaceOrientationLandscapeRight?(kStatusBarSafeMargin+5):5);
            make.right.mas_offset(toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft?(-5-kStatusBarSafeMargin):-5);
            make.top.mas_offset(5);
            make.bottom.mas_offset(0);
            //make.height.mas_equalTo(250);
        }];
        [_chartView.layer layoutIfNeeded];
    }else{

    }
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
    [_chartView setHidden:NO];
}
#pragma clang diagnostic pop

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(nonnull id<UIViewControllerTransitionCoordinator>)coordinator{
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
    if(@available(iOS 16.0, *)) {
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        if (scene.interfaceOrientation == UIInterfaceOrientationLandscapeLeft||scene.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
            [_chartView mas_updateConstraints:^(MASConstraintMaker *make) {
                
                make.left.mas_offset(scene.interfaceOrientation == UIInterfaceOrientationLandscapeRight?(+5+kSafe_top):5);
                make.right.mas_offset(scene.interfaceOrientation == UIInterfaceOrientationLandscapeLeft?(-5-kSafe_top):-5);
                make.top.mas_offset(5);
                make.bottom.mas_offset(0);
                //make.height.mas_equalTo(250);
            }];
            [_chartView.layer layoutIfNeeded];
            [_chartView setHidden:NO];
        }
    }else{
        [_chartView setHidden:NO];
    }
}

//#pragma mark 强制横屏(针对present方式)
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
//    return UIInterfaceOrientationMaskLandscapeRight;
//}
//
//-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
//    return UIInterfaceOrientationLandscapeRight;
//}


//- (void)willTransitionToTraitCollection:(UITraitCollection *)newCollection withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{
//    if (newCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact && newCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
//
//        NSLog(@"竖屏");
//
//    }
//
//    if (newCollection.horizontalSizeClass == UIUserInterfaceSizeClassCompact && newCollection.verticalSizeClass == UIUserInterfaceSizeClassRegular) {
//        NSLog(@"横屏");
//    }
//
//}
//
//- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(nonnull id<UIViewControllerTransitionCoordinator>)coordinator{
//
//}

//-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
//{
//    // do something before rotation
//    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
//
//
//    }else{
//
//    }
//  }

//-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
//{
//    // do something after rotation
//
//}

@end
